package com.haiheng.library_base.mqtt
import android.util.Log
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import java.util.*

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/4/28 0028
 * @Version: 1.0
 */

class MqttClientHelper(private val clientId: String, private val brokerUrl: String,
                       private val username: String, private val passwordt: String) {

    private lateinit var mqttClient: MqttClient
    private var isConnected = false
    private var isConnecting = false
    private val TAG = "MqttClientHelper"

    private val options = MqttConnectOptions().apply {
        isAutomaticReconnect = false
        isCleanSession = true
        userName = username
        password = passwordt.toCharArray()
    }

    private val persistence = MemoryPersistence()

    fun connect() {
        LogUtils.d("连接信息 clientId:$clientId  brokerUrl:$brokerUrl  userName:$username  password:$passwordt")
        if (isConnected || isConnecting) return

        isConnecting = true
        mqttClient = MqttClient(brokerUrl, clientId, persistence)

        mqttClient.setCallback(object : MqttCallbackExtended {
            override fun connectComplete(reconnect: Boolean, serverURI: String?) {
                isConnected = true
                isConnecting = false
               LogUtils.d("${TAG} Connected to: $brokerUrl")
//                subscribe(TOPIC,QOS)
            }

            override fun connectionLost(cause: Throwable?) {
                isConnected = false
                if (isConnecting) {
                   LogUtils.d("${TAG} Connecting failed: $brokerUrl")
                    isConnecting = false
                    return
                }
               LogUtils.e("${TAG} Connection lost: $brokerUrl  cause:${cause?.message}")
//                reconnect()
            }

            override fun messageArrived(topic: String?, message: MqttMessage?) {
                message?.let {
                   LogUtils.d("${TAG} Message received: $topic - ${it.payload} message:${message.toString()}")
                }

            }

            override fun deliveryComplete(token: IMqttDeliveryToken?) {
               LogUtils.d("${TAG} Delivery complete: ${token?.message}")
            }
        })

        try {
            mqttClient.connect(options)
        } catch (e: MqttException) {
            isConnecting = false
            e.printStackTrace()
            LogWriter.e("${TAG} Failed to connect: $brokerUrl ex:${e.message}")
//            reconnect()
        }
    }

    fun unsubscribe(topic: String){
        try {
            mqttClient.unsubscribe(topic)

        }catch (ex:Exception){
            LogWriter.e("取消订阅异常：${ex.message}")
        }
    }


    fun disconnect() {
        if (!isConnected) return
        try {
            mqttClient.disconnect()
            mqttClient.close()
            isConnected = false
           LogUtils.d("${TAG} Disconnected from: $brokerUrl")
        } catch (e: MqttException) {
            e.printStackTrace()
            LogUtils.e("${TAG} Failed to disconnect: $brokerUrl")
        }
    }

    fun subscribe(topic: String, qos: Int = 0) {
        if (!isConnected) return
        try {
            mqttClient.subscribe(topic, qos)
            LogUtils.d("${TAG} 订阅成功 Subscribed to: $topic")
        } catch (e: MqttException) {
            e.printStackTrace()
            LogUtils.e("${TAG} 订阅失败 Failed to subscribe to: $topic")
        }
    }

    fun publish(topic: String, message: String, qos: Int = 0, retained: Boolean = false) {
        if (!isConnected) return
        try {
            mqttClient.publish(topic, message.toByteArray(), qos, retained)
            LogUtils.d("${TAG} 发布成功 Published message: $message to topic: $topic")
        } catch (e: MqttException) {
            e.printStackTrace()
            LogUtils.e("${TAG} 发布失败:Failed to publish message: $message to topic: $topic")
        }
    }

    fun reconnect() {

//        Thread {
//            while (!mqttClient.isConnected) {
//                try {
//                    mqttClient.connect(options)
//                } catch (ex: Exception) {
//                    LogUtils.e("${TAG} 重连失败:${ex.message}")
//                    ex.printStackTrace()
//                }
//            }
//        }.start()
         if (!mqttClient.isConnected) {
             try {
//                    Thread.sleep(RECONNECT_DELAY)
//                    connect()
                 mqttClient.reconnect()
             } catch (ex: Exception) {
                 LogUtils.e("${TAG} 重连失败:${ex.message}")
                 ex.printStackTrace()
             }
         }
    }



}

